package scenic.jni;

import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;

public class RenderCanvas extends Canvas {
	private static final long serialVersionUID = 1L;

	static {
		System.loadLibrary("ScenicJNI");
//		System.load("/usr/lib/libScenicJNI.so");
	}
	
	private int context = 0;
	private int width;
	private int height;
	
	private class CanvasHierarchyListener implements HierarchyListener {
		public void hierarchyChanged(HierarchyEvent e) {
			if((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0) {
				if(!isShowing())
					release();
			}
		}
	}
	
	public RenderCanvas()
	{
		super(XCanvas.findConfiguration(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()));
		addHierarchyListener(new CanvasHierarchyListener());
	}
	
	public void paint(Graphics g) {
		if(context == 0) {
			context = createContext();
			width = getWidth();
			height = getHeight();
		}
		else if(width != getWidth() || height != getHeight()) {
			resetContext(context);
			width = getWidth();
			height = getHeight();
		}
	}
	
	public void release() {
		if(context != 0) {
			Renderer renderer = new Renderer();
			renderer.release(context);
			context = 0;
		}		
	}
	
	public void finalize() {
		release();
	}
	
	public void update(Graphics g) {
		paint(g);
	}
	
	private native int createContext();
	private native void resetContext(int context);
	
	public int getContext() {
		return context;
	}
	
	public boolean getIsIntialized() {
		return context != 0;
	}
}
